package ro.sobis.repetor;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class InregistrareSuporter implements Runnable {
	private Log log = LogFactory.getLog(InregistrareSuporter.class);
	Socket socketSuporter;
	InputStream inputStream;
	Thread t;
	public InregistrareSuporter(Socket s) {
		socketSuporter=s;

		try{
			inputStream = socketSuporter.getInputStream();
		}catch(IOException e)
		{
			log.error(e.getMessage());
		}

		t= new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		int bufLen=512;
		byte buf[]= new byte[bufLen];
		int bytesCititi;

		while(true)
		{
			try
			{
				bytesCititi = inputStream.read(buf, 0, bufLen);
				byte enc [] = new byte[bytesCititi];
				System.arraycopy(buf, 0, enc, 0, bytesCititi);
				EncryptDecrypt ed = new EncryptDecrypt();

				String dateConexiune[] = ed.decrypt(enc).split("###");

				Hashtable<String, String> env = new Hashtable<String, String>();
				env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
				env.put(Context.SECURITY_AUTHENTICATION, "simple");
				env.put(Context.PROVIDER_URL, "ldap://localhost:389");
				env.put(Context.SECURITY_PRINCIPAL, dateConexiune[0]);
				env.put(Context.SECURITY_CREDENTIALS, dateConexiune[1]);
				DirContext ctx;
				ctx = new InitialDirContext(env);

				String numeServerRemote = dateConexiune[2]; 


				Socket socketClient= Repetor.getClienti().get(numeServerRemote);
				if(socketClient!=null)
				{
					socketClient.getOutputStream().write(1); //initializea conexiunea clientului pe portrul 1352
					socketSuporter.getOutputStream().write(1);//initializeaza severul mock-up pe statia suporterului pe portul 1352
					
					ForwardConexiune inHandler = new ForwardConexiune(socketClient, socketSuporter);
					ForwardConexiune outHandler = new ForwardConexiune(socketSuporter, socketClient);
				}

			}
			catch(Exception ex)
			{	
				try {
					socketSuporter.close();
				} catch (IOException e) {e.printStackTrace();}
				log.error(ex.getMessage());
				return;
			}
		}
	}

}
